﻿namespace ChinaUnicom.Parser.Parsers
{
    using ChinaUnicom.Models;
    using HtmlAgilityPack;
    using System.Linq;

    internal class ClientParser : IItemsParser
    {
        public ItemType Type
        {
            get { return ItemType.Client; }
        }

        public ItemCollection Parse(string html)
        {
            ItemCollection items = new ItemCollection();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html.Replace("&nbsp;", string.Empty));
            var contents = doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "mrlf2").ToList();

            // base info
            string name = string.Empty;
            foreach (HtmlNode node in contents[0].ChildNodes)
            {
                if (node.Name == "#text" && name == string.Empty)
                {
                    name = node.InnerText.InnerTextTrim();
                }
                else if (node.Name == "span" && name != string.Empty)
                {
                    items.Add(new Item { Name = name, Value = node.InnerText.InnerValueTrim() });
                    name = string.Empty;
                }
            }

            // more info
            name = string.Empty;
            foreach (HtmlNode node in contents[1].ChildNodes)
            {
                if (node.Name == "#text" && name == string.Empty)
                {
                    name = node.InnerText.InnerTextTrim();
                }
                else if (node.Name == "span" && name != string.Empty)
                {
                    items.Add(new Item { Name = name, Value = node.InnerText.InnerValueTrim() });
                    name = string.Empty;
                }
            }

            return items;
        }
    }
}
